<?php
jimport( 'joomla.application.component.view');
jimport('joomla.html.pagination');

class DataGrid
{
	var $_datatable;
	var $_colheaders;
	var $_tablename;
    var $_limit;
    var $_limitstart;
    var $_ordering;
    var $_orderingDirection;
    var $_query;
    var $_tabSelected;		// 1 - Query, 2 - Browse, 3 - Structure

	function DataGrid($tname, $qry, $tab)
	{
		$this->_query = $qry;
		$this->_tabSelected = $tab;
		$this->_tablename = $tname;
	}

	function bindGrid($objView)
	{
		$db = &JFactory::getDBO();
		if($this->_tabSelected <> 3 && $this->_ordering <> ''){
			$this->_query .= ' ORDER BY  '.$this->_ordering.' '.$this->_orderingDirection;
		}
		$this->_datatable = $this->getTableData();
 
		$cctable = '';

		if(count($this->_datatable) > 0){
			$cctable = '<table name="tblGrid" id="tblGrid" class="adminlist" cellspacing=0 cellpadding=2 ><thead><tr>';
			$cctable .= '<th class="ccgridrownumheader">#</th>';

			if($this->_tabSelected == 2){
				$cctable .= '<th class="ccgridrownumheader" >&nbsp;</th>';
				$cctable .= '<th class="ccgridrownumheader" >&nbsp;</th>';
			}
			$cctable .= '<input type=hidden id="colcount" name="colcount" value="'.count($this->_datatable[0]).'"/>';

			$index = 1;
			foreach($this->_datatable[0] as $key=>$col) {
				if($this->_tabSelected <> 3){
					$cctable .= '<th>'.JHTML::_('grid.sort', $key, $key, $this->_orderingDirection, $this->_ordering == $key);
				}
				else{
					$cctable .= '<th>'.$key;
				}
				$cctable .= '<input type=hidden id="colname_'.$index.'" name="colname_'.$index.'" value="'.$key.'" /></th>';
				$index++;
			}

			$cctable .= '</tr></thead><tbody>';

			$rowIndex = 1;

			foreach($this->_datatable as $rows){

				$cctable .= '<tr id="tr_'.$rowIndex.'" name="tr_'.$rowIndex.'" class="row'.($rowIndex % 2).'">';
				$cctable .= '<td class="ccgridrownum">'.($this->_limitstart + $rowIndex).'</td>';

				$colIndex = 1;

				if($this->_tabSelected == 2){
					$cctable .= '<td style="text-align:center;" id="td_'.$rowIndex.'_'.$colIndex.'" >';
					$cctable .= '<img style="cursor:pointer;" title = "Edita" id="imgEdit_'.$rowIndex.'"  src="components/com_sialpacadb/assets/images/edit.png" onclick="editClick_Handler('.$rowIndex.','.$colIndex.', this);"></td>';
					$cctable .= '<td style="text-align:center;" id="td_'.$rowIndex.'_'.$colIndex.'" >';
					$cctable .= '<img style="cursor:pointer;" title="Cancella" id="imgDelete_'.$rowIndex.'" src="components/com_sialpacadb/assets/images/delete.png" onclick="deleteClick_Handler('.$rowIndex.','.$colIndex.', this);"></td>';
				}

				foreach($rows as $key=>$col) {
					
					if($this->_tabSelected == 3 && ($colIndex == 3 || $colIndex == 4)){
						$cctable .= '<td name="td_'.$rowIndex.'_'.$colIndex.'" id="td_'.$rowIndex.'_'.$colIndex.'" style="text-align:center;" title="'.($col).'">';
						if($colIndex == 3){
							if(trim($col) == 'NO'){
								$cctable .= '&nbsp;';
							}
							else{
								$cctable .= '<img style="width:10px; height:10px;" src="components/com_sialpacadb/assets/images/tick.png" />';		
							}
						}
						elseif($colIndex == 4){
							if(trim($col) == 'PRI'){
								$cctable .= '<img style="" src="components/com_sialpacadb/assets/images/bullet_key.png" />';
							}
							else{
								$cctable .= '&nbsp;';		
							}
						}
					}
					else{
						$tooltip = '';
						$cctable .= '<td name="td_'.$rowIndex.'_'.$colIndex.'" id="td_'.$rowIndex.'_'.$colIndex.'" title="'.($tooltip).'">';
						if(strlen($col) > 50){
							$cctable .= '<span class="hasTip" title="'.$key.'::'.$objView->escape($col).'">'.$objView->escape(substr($col, 0, 50)).'...</span>';
						}
						else{
							$cctable .= $objView->escape($col);
						}
					}

					if($this->_tabSelected == 2){
						$cctable .= '<input type=hidden id="'.$key.'_'.$rowIndex.'" name="'.$key.'_'.$rowIndex.'" value="'.$col.'">';
					}
					$cctable .= '&nbsp;</td>';
					$colIndex++;
				}
				$cctable .= '</tr>';
				$rowIndex++;
			}
			$cctable .= '</tbody></table>';

			if($this->getTotal() > 5 && $this->_tabSelected <> 3 ){
				$pagination = new JPagination($this->getTotal(), $this->_limitstart, $this->_limit);
				$cctable .= '<br>'.$pagination->getListFooter();
			}
		}
		elseif($this->_tabSelected == 2){
			$this->_colheaders = $db->getTableFields($this->_tablename);
			$cctable = '<table name="tblGrid" id="tblGrid" class="adminlist" cellspacing=0 cellpadding=2 ><thead><tr>';
			$cctable .= '<th >#</td>';

			foreach($this->_colheaders as $header ){
				foreach($header as $key => $fld){
					$cctable .= '<th>'.JHTML::_('grid.sort', $key, $key, $this->_orderingDirection, $this->_ordering == $key).'</td>';
				}
			}
			$cctable .= '</tr></thead><tbody><tr><td colspan=100 class="ccnodatagound">Nessun record presente</td>';
			$cctable .= '</tr></tbody></table>';
		}
		return $cctable;
	}

    function setLimits($limitstart, $limit)
    {
        $this->_limitstart = $limitstart;
        $this->_limit = $limit;
    }

	function getTableData()
	{
		$db = &JFactory::getDBO();
		$db->setQuery($this->_query, $this->_limitstart, $this->_limit);
		
		$items = ($items = $db->loadAssocList())?$items :array() ;
		return $items;
    }

    function getTotal()
    {
		$db  = &JFactory::getDBO();
		$ar  = split(' from ', strtolower($this->_query));
        $qry = 'SELECT COUNT(*) FROM '.$ar[1];

        $db->setQuery($qry);
        return $db->loadResult();
    }

    function setOrdering($ordering, $orderingDirection)
    {
        $this->_ordering = $ordering;
        $this->_orderingDirection = $orderingDirection;
        //error_log($this->_ordering .'--'. $this->_orderingDirection,3,"zompa.log");
    }  
    
	function bindEditableGrid($isForEdit, $data)
	{
		$db 			= &JFactory::getDBO();
		$this->_datatable = $this->getTableData();

		$cctable = '';

		if(count($this->_datatable) > 0){
			$cctable = '<table name="tblGrid" id="tblGrid" class="adminlist" cellspacing=0 cellpadding=2 ><thead><tr>';
			$cctable .= '<th class="ccgridrownumheader">#</th>';

			$cctable .= '<th class="ccgridheader">Nome Campo</th>';
	//		$cctable .= '<th class="ccgridheader">Datatype</th>';
			$cctable .= '<th >Valore</th>';

			$cctable .= '</tr></thead><tbody>';

			$rowIndex = 1;

			foreach($this->_datatable as $rows){
				if (strtolower($rows['Field']) == 'id'){
					continue;
			   }
				$cctable .= '<tr  id="tr_'.$rowIndex.'" name="tr_'.$rowIndex.'" class="row'.($rowIndex % 2).'">';
				$cctable .= '<td class="ccgridrownum">'.$rowIndex.'</td>';

				$colIndex = 1;

				$cctable .= '<td >'.$rows['Field'].'</td>';
		//		$cctable .= '<td >'.$rows['Type'].'</td>';
				$cctable .= '<td >';

				$colvalue = $data[$rows['Field'].'_'.$data['rowid']];

				$cctable .= '<input type=hidden name="colname_'.$rowIndex.'" id="colname_'.$rowIndex.'" value="'.$rows['Field'].'" />';
				$cctable .= '<input type=hidden name="colvalue_'.$rowIndex.'" id="colvalue_'.$rowIndex.'" value="'.$colvalue.'" />';

				if(strpos('a'.$rows['Type'], 'text') > 0 ){
					$cctable .= '<textarea rows=4 class="cctextarea" id="'.$rows['Field'].'" name="'.$rows['Field'].'">'.$colvalue.'</textarea>';
				}
				elseif(strpos('a'.$rows['Type'], 'int') > 0 ){
					$cctable .= '<input type=text class="cctextfieldint" id="'.$rows['Field'].'" value="'.$colvalue.'" name="'.$rows['Field'].'" />';
				}
				elseif(strpos('a'.$rows['Type'], 'time') > 0 ){
					$cctable .= '<input type=text class="cctextfieldtime" id="'.$rows['Field'].'" value="'.$colvalue.'"  name="'.$rows['Field'].'" />';
				}
				else{
					$cctable .= '<input type=text class="cctextfield" id="'.$rows['Field'].'" value="'.$colvalue.'"  name="'.$rows['Field'].'" />';
				}

				$cctable .= '</td>';

				$cctable .= '</tr>';
				$rowIndex++;
			}
			$cctable .= '</tbody></table>';
			$cctable .= '<input type="hidden" name="colcount" id="colcount" value="'.($rowIndex-1).'" />';
		}
		return $cctable;
	}
	function getStaticTab($mytab,$myindex){
		$db	= &JFactory::getDBO();
		$myquery= "SELECT * FROM jos_sialpaca_" . $mytab;
		$db->setQuery($myquery);
		$mylista= $db->loadAssocList();
		$mkselect = '<select id="sel_'.$mytab.'" name="'.$mytab.'">';
		$mkselect .= '<option value="off">Scegli...</option>';
		if (!empty($mylista)){
			foreach($mylista as $myval){
					$mkselect .= "<option value=\"".$myval['id']."\"";
					if($myval['id']==$myindex){
						$mkselect .= 'selected="selected" ';
					}
					$mkselect .= ">".$myval[$mytab]."</option>";	   
			}		
		}
		$mkselect .= '</select>';
		//error_log(print_r($mkselect,true),3,"zompa.log");
		return $mkselect;
	}
	function bindEditableGridPet($isForEdit, $data)
	{
		$db 			= &JFactory::getDBO();
		$this->_datatable = $this->getTableData();
		 //error_log(print_r($data,true),3,"zompa.log");
		
		$cctable = '';
       
		if(count($this->_datatable) > 0){
			$cctable = '<table name="tblGrid" id="tblGrid" class="adminlist" cellspacing=0 cellpadding=2 style="width:50%;"><thead><tr>'."\n";
			$cctable .= '<th class="ccgridrownumheader">#</th>'."\n";

			$cctable .= '<th class="ccgridheader">Nome campo</th>'."\n";
//			$cctable .= '<th class="ccgridheader">Datatype</th>';
			$cctable .= '<th >Valore</th>'."\n";

			$cctable .= '</tr></thead><tbody>'."\n";

			$rowIndex = 1;

			foreach($this->_datatable as $rows){
			   // id e' automatico
   			if (strtolower($rows['Field']) == 'id'){
	   		   continue;
			   }
				$cctable .= '<tr  id="tr_'.$rowIndex.'" name="tr_'.$rowIndex.'" class="row'.($rowIndex % 2).'">'."\n";
				$cctable .= '<td class="ccgridrownum">'.$rowIndex.'</td>'."\n";

				$colIndex = 1;

				$cctable .= '<td>'.$rows['Field'].'</td>'."\n";
	//			$cctable .= '<td>'.$rows['Type'].'</td>';
				$cctable .= '<td>'."\n";
				$colvalue = $data[$rows['Field'].'_'.$data['rowid']];
           
				$cctable .= '<input type="hidden" name="colname_'.$rowIndex.'" id="colname_'.$rowIndex.'" value="'.$rows['Field'].'" />'."\n";
				$cctable .= '<input type="hidden" name="colvalue_'.$rowIndex.'" id="colvalue_'.$rowIndex.'" value="'.$colvalue.'" />'."\n";
             
				if (strtolower($rows['Field']) == 'colore'){
					$cctable .= $this->getStaticTab('colore',$colvalue);	
					//	$cctable .= $mkcolore;
				} elseif(strtolower($rows['Field']) == 'tipo')
				{
					$cctable .= $this->getStaticTab('tipo',$colvalue);
   				//$cctable .= $mktipo;
   				
				}elseif(strtolower($rows['Field']) == 'sesso')
				{
					$cctable .= $this->getStaticTab('sesso',$colvalue);
   				//$cctable .= $mksesso;
   				
				} elseif(strtolower($rows['Field']) == 'status')
				{
					$cctable .= $this->getStaticTab('status',$colvalue);
   				//$cctable .= $mkstatus;
   				
				}elseif(strtolower($rows['Field']) == 'uid')
				{
					if ($colvalue==""){
						$colvalue = $this->uuid();
					}
					$cctable .= '<input type="text" class="cctextfield" id="'.$rows['Field'].'" value="'.$colvalue.'" name="'.$rows['Field'].'" />';
  				  				
				}elseif(strtolower($rows['Field']) == 'padre')
				{
					$cctable .= '<A href="index3.php?option=com_sialpacadb&view=newgen"  rel="{handler: \'iframe\', size: {x: 370, y: 370}}" class="modal" ><img name="mkdodal" src="components/com_sialpacadb/assets/images/add-icon.gif" border="0" alt="Aggiungi valori" /></A>&nbsp;&nbsp;';
					$cctable .= '<input type="text" class="cctextfieldint" id="'.$rows['Field'].'" value="'.$colvalue.'" name="'.$rows['Field'].'" />';
   							
				}elseif(strtolower($rows['Field']) == 'fibra')
				{
					//$cctable .= '<A href="#" onclick="mkmodal(\'fibra\',\'id_animale\');" ><img name="mkdodal" src="components/com_sialpacadb/assets/images/add-icon.gif" border="0" alt="Aggiungi valori" /></A>&nbsp;&nbsp;';
					//$cctable .= '<input type="text" class="cctextfieldint" id="'.$rows['Field'].'" value="'.$colvalue.'" name="'.$rows['Field'].'" />';
                    $cctable .= '<A href="index3.php?option=com_sialpacadb&view=newfib"  rel="{handler: \'iframe\', size: {x: 370, y: 370}}" class="modal" ><img name="mkdodal" src="components/com_sialpacadb/assets/images/add-icon.gif" border="0" alt="Aggiungi valori" /></A>&nbsp;&nbsp;';
					$cctable .= '<input type="text" class="cctextfieldint" id="'.$rows['Field'].'" value="'.$colvalue.'" name="'.$rows['Field'].'" />';
   					
   							
				}elseif(strtolower($rows['Field']) == 'codallev')
				{
					$cctable .= '<input type="text" class="cctextfieldint" id="'.$rows['Field'].'" value="'.$colvalue.'" name="'.$rows['Field'].'" />';
   							
				}else{
				   

				   if(strpos('a'.$rows['Type'], 'text') > 0 ){
					   $cctable .= '<textarea rows=4 class="cctextarea" id="'.$rows['Field'].'" name="'.$rows['Field'].'"></textarea>';
				   }
				   elseif(strpos('a'.$rows['Type'], 'int') > 0 ){
					   $cctable .= '<input type="text" class="cctextfieldint" id="'.$rows['Field'].'" value="'.$colvalue.'" name="'.$rows['Field'].'" />';
				   }
				   elseif(strpos('a'.$rows['Type'], 'time') > 0 ){
					   $cctable .= '<input type="text" class="cctextfieldtime" id="'.$rows['Field'].'" value="'.$colvalue.'"  name="'.$rows['Field'].'" />';
				   }
				   elseif(strpos('a'.$rows['Type'], 'date') > 0 ){
					   $cctable .= '<A href="#" onclick="displayDatePicker(\''.$rows['Field'].'\',this);" ><img name="calend" src="components/com_sialpacadb/assets/images/calendar-icon.jpg" border="0" alt="Calendario" /></A>&nbsp;&nbsp;';
					   $cctable .= '<input type="text" class="cctextfielddate" id="'.$rows['Field'].'" value="'.$colvalue.'" name="'.$rows['Field'].'" />';
					   
				   }else{
					   $cctable .= '<input type="text" class="cctextfield" id="'.$rows['Field'].'" value="'.$colvalue.'" name="'.$rows['Field'].'" />';
				   }
            }
				$cctable .= '</td>';

				$cctable .= '</tr>';
				$rowIndex++;
			   
			}
			$cctable .= '</tbody></table>';
			$cctable .= '<input type=hidden name="colcount" id="colcount" value="'.($rowIndex-1).'" />';
		}
		return $cctable;
	}
	function uuid($prefix = '')
	{
		$chars = md5(uniqid(mt_rand(), true));
		$uuid  = substr($chars,0,8) . '-';
		$uuid .= substr($chars,8,4) . '-';
		$uuid .= substr($chars,12,4) . '-';
		$uuid .= substr($chars,16,4) . '-';
		$uuid .= substr($chars,20,12);
		return $prefix . $uuid;
	}
 }
?>
